<template>
  <div class="statistics-container">
    <div class="page-header">
      <h1>数据统计</h1>
      <div class="date-filter">
        <select v-model="dateRange" @change="updateStatistics">
          <option value="7">近7天</option>
          <option value="30">近30天</option>
          <option value="90">近90天</option>
          <option value="365">近一年</option>
        </select>
        <button class="refresh-button" @click="refreshData">
          <i class="fa fa-sync-alt"></i>
          刷新数据
        </button>
      </div>
    </div>
    
    <!-- 核心指标 -->
    <div class="metrics-grid">
      <div class="metric-card">
        <div class="metric-icon views-icon"><i class="fa fa-eye"></i></div>
        <div class="metric-content">
          <div class="metric-number">{{ totalViews.toLocaleString() }}</div>
          <div class="metric-label">总播放量</div>
          <div class="metric-change" :class="{ positive: viewsChange >= 0, negative: viewsChange < 0 }">
            <i class="fa" :class="viewsChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(viewsChange) }}%
          </div>
        </div>
      </div>
      
      <div class="metric-card">
        <div class="metric-icon users-icon"><i class="fa fa-users"></i></div>
        <div class="metric-content">
          <div class="metric-number">{{ totalUsers.toLocaleString() }}</div>
          <div class="metric-label">总用户数</div>
          <div class="metric-change" :class="{ positive: usersChange >= 0, negative: usersChange < 0 }">
            <i class="fa" :class="usersChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(usersChange) }}%
          </div>
        </div>
      </div>
      
      <div class="metric-card">
        <div class="metric-icon members-icon"><i class="fa fa-crown"></i></div>
        <div class="metric-content">
          <div class="metric-number">{{ totalMembers.toLocaleString() }}</div>
          <div class="metric-label">付费会员</div>
          <div class="metric-change" :class="{ positive: membersChange >= 0, negative: membersChange < 0 }">
            <i class="fa" :class="membersChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(membersChange) }}%
          </div>
        </div>
      </div>
      
      <div class="metric-card">
        <div class="metric-icon animes-icon"><i class="fa fa-film"></i></div>
        <div class="metric-content">
          <div class="metric-number">{{ totalAnimes.toLocaleString() }}</div>
          <div class="metric-label">动漫数量</div>
          <div class="metric-change" :class="{ positive: animesChange >= 0, negative: animesChange < 0 }">
            <i class="fa" :class="animesChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(animesChange) }}%
          </div>
        </div>
      </div>
    </div>
    
    <!-- 趋势图表 -->
    <div class="charts-section">
      <div class="chart-card">
        <div class="chart-header">
          <h3>趋势分析</h3>
          <div class="chart-controls">
            <button 
              v-for="type in trendTypes" 
              :key="type.value"
              :class="['trend-button', { active: trendType === type.value }]"
              @click="trendType = type.value"
            >
              {{ type.label }}
            </button>
          </div>
        </div>
        <div class="chart-container">
          <canvas id="trendChart"></canvas>
        </div>
      </div>
      
      <!-- 会员分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>会员类型分布</h3>
        </div>
        <div class="chart-container pie-chart">
          <canvas id="pieChart"></canvas>
        </div>
      </div>
    </div>
    
    <!-- 热门动漫 -->
    <div class="popular-section">
      <div class="section-header">
        <h3>热门动漫</h3>
        <div class="sort-controls">
          <label>排序方式：</label>
          <select v-model="sortBy" @change="updatePopularAnimes">
            <option value="views">播放量</option>
            <option value="rating">评分</option>
          </select>
        </div>
      </div>
      
      <div class="popular-list">
        <div 
          v-for="(anime, index) in popularAnimes" 
          :key="anime.id"
          class="popular-item"
        >
          <div class="rank">{{ index + 1 }}</div>
          <div class="anime-info">
            <div class="anime-cover">
              <img :src="anime.cover" :alt="anime.title">
            </div>
            <div class="anime-details">
              <h4>{{ anime.title }}</h4>
              <div class="anime-meta">
                <span class="views"><i class="fa fa-eye"></i> {{ anime.views.toLocaleString() }}</span>
                <span class="rating"><i class="fa fa-star"></i> {{ anime.rating }}</span>
                <span class="category">{{ anime.category }}</span>
              </div>
            </div>
          </div>
          <div class="trend-indicator" :class="anime.trend">
            <i class="fa" :class="anime.trend === 'up' ? 'fa-arrow-up' : anime.trend === 'down' ? 'fa-arrow-down' : 'fa-minus'"></i>
            {{ anime.trendValue }}%
          </div>
        </div>
      </div>
    </div>
    
    <!-- 地域分布 -->
    <div class="region-section">
      <div class="section-header">
        <h3>用户地域分布</h3>
      </div>
      <div class="region-list">
        <div 
          v-for="region in regionData" 
          :key="region.name"
          class="region-item"
        >
          <div class="region-name">{{ region.name }}</div>
          <div class="region-bar">
            <div class="region-bar-fill" :style="{ width: region.percentage + '%' }"></div>
          </div>
          <div class="region-info">
            <span class="region-count">{{ region.count.toLocaleString() }}</span>
            <span class="region-percentage">{{ region.percentage }}%</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入Chart.js核心和需要的组件
import { Chart, registerables } from 'chart.js'
// 注册所有组件
Chart.register(...registerables)

export default {
  name: 'StatisticsView',
  data() {
    return {
      // 日期范围
      dateRange: '30',
      
      // 核心指标数据
      totalViews: 1234567,
      totalUsers: 54321,
      totalMembers: 12345,
      totalAnimes: 856,
      
      // 变化率
      viewsChange: 12.5,
      usersChange: 8.3,
      membersChange: 15.7,
      animesChange: 5.2,
      
      // 趋势图配置
      trendType: 'views',
      trendTypes: [
        { label: '播放量', value: 'views' },
        { label: '用户数', value: 'users' },
        { label: '会员数', value: 'members' },
      ],
      
      // 热门动漫排序
      sortBy: 'views',
      
      // 趋势数据
      trendData: {
        labels: [],
        views: [],
        users: [],
        members: [],
      },
      
      // 热门动漫数据
      popularAnimes: [
        {
          id: 1,
          title: '鬼灭之刃 游郭篇',
          cover: '/src/assets/鬼灭之刃.jpeg',
          views: 1254000,
          rating: 9.5,
          category: '热血',
          trend: 'up',
          trendValue: 15.3,
        },
        {
          id: 2,
          title: '进击的巨人 最终季',
          cover: '/src/assets/进击的巨人.jpg',
          views: 987000,
          rating: 9.3,
          category: '奇幻',
          trend: 'up',
          trendValue: 8.7,
        },
        {
          id: 3,
          title: '黑神话：悟空',
          cover: '/src/assets/黑神话.jpeg',
          views: 876000,
          rating: 9.7,
          category: '动作',
          trend: 'up',
          trendValue: 23.5,
        },
        {
          id: 4,
          title: '原神',
          cover: '/src/assets/原神.jpg',
          views: 765000,
          rating: 9.1,
          category: '冒险',
          trend: 'down',
          trendValue: 2.1,
        },
        {
          id: 5,
          title: '咒术回战',
          cover: '/src/assets/咒术回战.jpg',
          views: 654000,
          rating: 9.2,
          category: '战斗',
          trend: 'up',
          trendValue: 12.4,
        },
      ],
      
      // 地域分布数据
      regionData: [
        { name: '北京', count: 12540, percentage: 15.3 },
        { name: '上海', count: 11230, percentage: 13.7 },
        { name: '广州', count: 9870, percentage: 12.1 },
        { name: '深圳', count: 9230, percentage: 11.3 },
        { name: '成都', count: 7650, percentage: 9.4 },
        { name: '杭州', count: 6780, percentage: 8.3 },
        { name: '武汉', count: 5430, percentage: 6.6 },
        { name: '南京', count: 4320, percentage: 5.3 },
        { name: '西安', count: 3890, percentage: 4.8 },
        { name: '重庆', count: 3450, percentage: 4.2 },
        { name: '其他', count: 5160, percentage: 6.3 },
      ],
      
      // 图表实例
      trendChart: null,
      pieChart: null,
    }
  },
  
  watch: {
    trendType() {
      this.$nextTick(() => {
        this.initTrendChart()
      })
    },
  },
  
  mounted() {
    this.generateTrendData()
    this.$nextTick(() => {
      this.updateCharts()
    })
  },
  
  beforeUnmount() {
    // 清理图表实例，避免内存泄漏
    try {
      if (this.trendChart) {
        this.trendChart.destroy()
        this.trendChart = null
      }
      if (this.pieChart) {
        this.pieChart.destroy()
        this.pieChart = null
      }
    } catch (error) {
      console.error('清理图表实例时出错:', error)
    }
  },
  
  methods: {
    // 生成趋势数据
    generateTrendData() {
      const days = parseInt(this.dateRange)
      const labels = []
      const viewsData = []
      const usersData = []
      const membersData = []
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        labels.push(`${date.getMonth() + 1}/${date.getDate()}`)
        
        // 生成模拟数据
        viewsData.push(Math.floor(Math.random() * 50000) + 30000)
        usersData.push(Math.floor(Math.random() * 2000) + 1000)
        membersData.push(Math.floor(Math.random() * 500) + 300)
      }
      
      this.trendData = {
        labels,
        views: viewsData,
        users: usersData,
        members: membersData,
      }
    },
    
    // 初始化趋势图表
    initTrendChart() {
      // 先清理旧图表，避免内存泄漏
      if (this.trendChart) {
        this.trendChart.destroy()
        this.trendChart = null
      }
      
      const chartElement = document.getElementById('trendChart')
      if (!chartElement) {
        console.warn('trendChart元素未找到，跳过图表初始化')
        return
      }
      
      try {
        const ctx = chartElement.getContext('2d')
        if (!ctx) {
          console.warn('无法获取trendChart的绘图上下文')
          return
        }
        
        // 确保有数据才初始化图表
        if (!this.trendData || !this.trendData.labels || !this.getTrendValues()) {
          console.warn('趋势数据不完整，跳过图表初始化')
          return
        }
        
        this.trendChart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: this.trendData.labels,
            datasets: [{
              label: this.getTrendLabel(),
              data: this.getTrendValues(),
              borderColor: '#3498db',
              backgroundColor: 'rgba(52, 152, 219, 0.1)',
              tension: 0.4,
              fill: true,
            }],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                display: false,
              },
              tooltip: {
                mode: 'index',
                intersect: false,
              },
            },
            scales: {
              y: {
                beginAtZero: true,
                ticks: {
                  callback: function(value) {
                    return value >= 1000 ? (value / 1000) + 'k' : value
                  },
                },
              },
              x: {
                grid: {
                  display: false,
                },
              },
            },
          },
        })
      } catch (error) {
        console.error('初始化趋势图表时出错:', error)
      }
    },
    
    // 初始化饼图
    initPieChart() {
      // 先清理旧图表，避免内存泄漏
      if (this.pieChart) {
        this.pieChart.destroy()
        this.pieChart = null
      }
      
      const chartElement = document.getElementById('pieChart')
      if (!chartElement) {
        console.warn('pieChart元素未找到，跳过图表初始化')
        return
      }
      
      try {
        const ctx = chartElement.getContext('2d')
        if (!ctx) {
          console.warn('无法获取pieChart的绘图上下文')
          return
        }
        
        this.pieChart = new Chart(ctx, {
          type: 'doughnut',
          data: {
            labels: ['月度会员', '季度会员', '年度会员', '终身会员'],
            datasets: [{
              data: [45, 25, 20, 10],
              backgroundColor: [
                '#3498db',
                '#2ecc71',
                '#e74c3c',
                '#9b59b6',
              ],
              borderWidth: 0,
            }],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'right',
              },
            },
            cutout: '60%',
            elements: {
              arc: {
                hoverOffset: 10,
              },
            },
          },
        })
      } catch (error) {
        console.error('初始化饼图时出错:', error)
      }
    },
    
    getTrendLabel() {
      switch (this.trendType) {
        case 'views': return '播放量'
        case 'users': return '用户数'
        case 'members': return '会员数'
        default: return '播放量'
      }
    },
    
    getTrendValues() {
      switch (this.trendType) {
        case 'views': return this.trendData.views
        case 'users': return this.trendData.users
        case 'members': return this.trendData.members
        default: return this.trendData.views
      }
    },
    
    updateStatistics() {
      this.generateTrendData()
      this.$nextTick(() => {
        this.updateCharts()
      })
    },
    
    updateCharts() {
      this.initTrendChart()
      this.initPieChart()
    },
    
    updatePopularAnimes() {
      this.popularAnimes.sort((a, b) => {
        if (this.sortBy === 'views') {
          return b.views - a.views
        } else {
          return b.rating - a.rating
        }
      })
    },
    
    refreshData() {
      // 模拟数据刷新
      this.totalViews = Math.floor(Math.random() * 100000) + 1200000
      this.totalUsers = Math.floor(Math.random() * 5000) + 54000
      this.totalMembers = Math.floor(Math.random() * 1000) + 12000
      this.totalAnimes = Math.floor(Math.random() * 100) + 850
      
      // 确保返回数字类型而不是字符串
      this.viewsChange = parseFloat((Math.random() * 20 - 5).toFixed(1))
      this.usersChange = parseFloat((Math.random() * 15 - 3).toFixed(1))
      this.membersChange = parseFloat((Math.random() * 25 - 5).toFixed(1))
      this.animesChange = parseFloat((Math.random() * 10 - 2).toFixed(1))
      
      this.updateStatistics()
      
      console.log('数据刷新成功')
    },
  },
}
</script>

<style scoped>
.statistics-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  overflow-x: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 15px;
}

.date-filter select {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

.refresh-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.refresh-button:hover {
  background: #2980b9;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.metric-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.metric-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.views-icon {
  background: #3498db;
}

.users-icon {
  background: #2ecc71;
}

.members-icon {
  background: #f39c12;
}

.animes-icon {
  background: #9b59b6;
}

.metric-content {
  flex: 1;
}

.metric-number {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1.2;
}

.metric-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.metric-change.positive {
  color: #2ecc71;
}

.metric-change.negative {
  color: #e74c3c;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-header h3 {
  color: #2c3e50;
  margin: 0;
  font-size: 18px;
}

.chart-controls {
  display: flex;
  gap: 8px;
}

.trend-button {
  padding: 6px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.trend-button:hover {
  background: #f8f9fa;
}

.trend-button.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.chart-container {
  height: 300px;
  position: relative;
}

.pie-chart {
  height: 250px;
}

.popular-section,
.region-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.section-header h3 {
  color: #2c3e50;
  margin: 0;
  font-size: 18px;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.sort-controls select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

.popular-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.popular-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: background-color 0.3s;
}

.popular-item:hover {
  background: #e9ecef;
}

.rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 14px;
}

.anime-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.anime-cover img {
  width: 60px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
}

.anime-details h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 16px;
}

.anime-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #7f8c8d;
}

.anime-meta .views,
.anime-meta .rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.anime-meta .rating {
  color: #f39c12;
}

.trend-indicator {
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-indicator.up {
  color: #2ecc71;
}

.trend-indicator.down {
  color: #e74c3c;
}

.trend-indicator.neutral {
  color: #95a5a6;
}

.region-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.region-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.region-name {
  width: 80px;
  font-size: 14px;
  color: #34495e;
}

.region-bar {
  flex: 1;
  height: 20px;
  background: #ecf0f1;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
}

.region-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #3498db, #2980b9);
  border-radius: 10px;
  transition: width 0.6s ease;
}

.region-info {
  min-width: 100px;
  text-align: right;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.region-count {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.region-percentage {
  font-size: 12px;
  color: #7f8c8d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .metrics-grid,
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .page-header,
  .chart-header,
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .popular-item {
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
  }
  
  .region-item {
    flex-wrap: wrap;
  }
  
  .region-info {
    width: 100%;
    text-align: left;
  }
}
</style>